/**
 * URL cache.
 *
 * @param _url
 *            URL to fetch.
 *
 */
function URLDataCache(theUrl) {
    /**
     * URL to cache.
     */
    var url = theUrl;
    /**
     * Timeout in milliseconds.
     */
    var timeout = 300000;
    /**
     * Last update time.
     */
    var lastUpdateTime = new Date().getTime();
    
    var response = {};
}

function DeliciousDataProvider(){
    this.loadAndCache = function(url, callback){
        console.log(["Create new info", url]);
        
        var info = new URLDataCache(url);
        
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.send();
        
        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4) {
                info.response = xhr.responseText;
                info.lastUpdateTime = new Date().getTime();
                localStorage.setItem(url, $.toJSON(info));
                callback(info);
            }
        };
    };
    
    /**
     * Get data for the url. Caches response.
     *
     * @param url
     *            URL to fetch.
     * @param callback
     *            Callback to call.
     * @return returns JSON response.
     */
    // TODO: Configure cache.
    this.getURL = function(url, callback){
        var info = localStorage.getItem(url);
        if (info) {
            info = $.evalJSON(info);
            
            if ((info.lastUpdateTime || 0) + (info.timeout || 300000) < new Date().getTime()) {
                this.loadAndCache(url, callback);
            }
            else {
                console.log("Reusing data from cache: " + url);
                callback(info);
            }
        }
        else {
            this.loadAndCache(url, callback);
        }
    };
    
    
}
